package com.c2b.algorithm.leetcode.base;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * <a href="https://leetcode.cn/problems/permutations/">全排列(Permutations)</a>
 * <p>给定一个不含重复数字的数组 nums ，返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。</p>
 *
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：nums = [1,2,3]
 *      输出：[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 *
 * 示例 2：
 *      输入：nums = [0,1]
 *      输出：[[0,1],[1,0]]
 *
 * 示例 3：
 *      输入：nums = [1]
 *      输出：[[1]]
 * </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 *  <ul>
 *      <li>1 <= nums.length <= 6</li>
 *      <li>-10 <= nums[i] <= 10</li>
 *      <li>nums 中的所有整数 互不相同</li>
 *  </ul>
 * </p>
 *
 * @author c2b
 * @see LC0046Permutations_M
 * @see LC0047Permutations_II_M
 * @since 2024/2/22 17:13
 */
public class LC0046Permutations_M {
    static class Solution {
        public List<List<Integer>> permute(int[] nums) {
            List<List<Integer>> resList = new ArrayList<>();

            dsf(nums.length, nums, new LinkedList<>(), new boolean[nums.length], resList);
            return resList;
        }

        private void dsf(int numsLength, int[] nums, Deque<Integer> path, boolean[] used, List<List<Integer>> resList) {
            if (path.size() == numsLength) {
                resList.add(new ArrayList<>(path));
                return;
            }
            for (int i = 0; i < numsLength; i++) {
                if (used[i]) {
                    continue;
                }
                path.addLast(nums[i]);
                used[i] = true;
                dsf(numsLength, nums, path, used, resList);
                path.removeLast();
                used[i] = false;
            }
        }
    }
}
